package com.owl.jdbc.context;

import com.owl.jdbc.properties.OwlProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanInitializationException;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 切换数据源上下文
 */
public class DBContextHolder {

    public static OwlProperties owlProperties;

    private final static Logger logger = LoggerFactory.getLogger(DBContextHolder.class);

    private static final ThreadLocal<String> contextHolder=new ThreadLocal<>();

    public static AtomicInteger slaveCounter = null;


    public static void set(String datasourceName){
        contextHolder.set(datasourceName);
    }

    public static String get() {
        return contextHolder.get();
    }
    public static void master() {
        contextHolder.remove();
        set("master");
        logger.info("切换到master");
    }

    public static void slave() {
        contextHolder.remove();
        if(slaveCounter ==null)
        {
            throw new BeanInitializationException("原子自增对象没有初始化");
        }
        //轮询自增 从库名称索引 = 自增变量%从库长度
        int index = slaveCounter.getAndIncrement() % owlProperties.getDatasource().getSlaves().length;
        String datasourceName = owlProperties.getDatasource().getSlaves()[index].getName();
        set(datasourceName);
        logger.info("切换到{}",datasourceName);
    }
}
